<?php

namespace app\common\services;

use Yii;

class UploadServices
{
    public static function Upload($file_name, $file_path)
    {
        if (!$file_name) {
            return['code' => -1, 'msg' => '文件名称不能为空'];
        }

        if (!$file_path) {
            return ['code' => -2, 'msg' => '路径不能空'];
        }

        $temp_file_extend = explode('.', $file_name);
        $file_type = strtolower(end($temp_file_extend));
        $image_key = md5(file_get_contents($file_path));
        $upload_dir_path = Yii::$app->getBasePath() . '/web/admin/uploads/';
        $folder_name = date('Ymd');
        $upload_dir = $upload_dir_path . $folder_name;
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0777, true);
            chmod($upload_dir, 0777);
        }
        $upload_full_name = $folder_name . '/' . $image_key . '.' . $file_type;
        if (is_uploaded_file($file_path)) {
            move_uploaded_file($file_path, $upload_dir_path . $upload_full_name);
        } else {
            file_put_contents($upload_dir_path . $upload_full_name, file_get_contents($file_path));
        }

        return['code' => 200, 'file_path' => $upload_full_name];
    }
}
